import requests
from lxml import etree

from day05.captcha_tool import solve_captcha

url = "https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx"
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
}

# 将验证码图片请求后保存到本地
session = requests.Session()
res_html = session.get(url=url, headers=headers).text
tree = etree.HTML(res_html)

# 获取验证码图片的 URL 路径
img_url = tree.xpath('//img[@id="imgCode"]/@src')[0]
full_img_url = "https://so.gushiwen.cn" + img_url

# 解析出动态变化的请求参数
__VIEWSTATE = tree.xpath('//input[@id="__VIEWSTATE"]/@value')[0]
print(f"__VIEWSTATE为:{__VIEWSTATE}")

# 下载验证码图片并保存为 PNG 格式
img_response = session.get(full_img_url)
with open("RandCode.png", "wb") as f:
    f.write(img_response.content)
print(f"验证码图片:RandCode.png")

# 处理验证码
result = solve_captcha(uname="13503450662", pwd="test123456", img_path='./RandCode.png', typeid=3)
print(f"验证码:{result}")

data = {
    "__VIEWSTATE": __VIEWSTATE,
    "__VIEWSTATEGENERATOR": "C93BE1AE",
    "from": "http://so.gushiwen.cn/user/collect.aspx",
    "email": "13503450662",
    "pwd": "test123456",
    "code": result,
    "denglu": "登录"
}

login_url = "https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx"
response = session.post(url=login_url, headers=headers, data=data)
# 检查登录是否成功
if "退出登录" in response.text:
    print("登录成功")

    # 将加载出来的页面保存到文件中
    with open("page.html", "w", encoding="utf-8") as f:
        f.write(response.text)
    print("页面已保存为 page.html")
else:
    print("登录失败")
